package com.example.btchat.client;

import java.io.IOException;
import java.io.InputStream;

import org.json.JSONException;

import com.example.btchat.Message;

import android.bluetooth.BluetoothSocket;
import android.widget.Toast;

public class ReaderThread extends Thread
{
	private InputStream input;
	private MainActivity parent;
	
	public ReaderThread(MainActivity parent, BluetoothSocket socket) throws IOException
	{
		this.parent = parent;
		this.input = socket.getInputStream();
	}
	
	@Override
	public void run()
	{
		String data;
		
		while(true)
		{
			data = "";
			ReaderThread.interrupted(); // clear interrupted flag
			
			try
			{
				while(input.available() > 0)
				{
					byte[] buffer = new byte[500];
					input.read(buffer);
					try
					{
						Thread.sleep(10);
					}
					catch(InterruptedException e)
					{}
					data += buffer;
				}
			}
			catch(IOException e)
			{
				this.onReadError();
				break;
			}
			
			if(data != "")
			{
				try
				{
					this.onMessageReceived(Message.fromString(data));
				}
				catch(JSONException e)
				{
					Toast.makeText(parent, R.string.error_on_receive, Toast.LENGTH_SHORT).show();
					return;
				}
			}
			else
			{
				try
				{
					Thread.sleep(1000);
				}
				catch(InterruptedException e)
				{}
			}
		}
	}
	
	private void onMessageReceived(final Message message)
	{
		parent.runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				parent.onMessageReceived(message);
			}
		});
	}
	
	private void onReadError()
	{
		parent.runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{
				parent.onReadError();
			}
		});
	}
}
